#!/usr/bin/env python
# -*- coding: utf-8 -*-

import fcntl
import os
import socket
import struct
import time
import urllib2


webip = '172.16.0.4'
vip = '172.16.0.3'

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
                            s.fileno(),
                            0x8915, # SIOCGIFADDR
                            struct.pack('256s', ifname[:15])
                            )[20:24])







def die_web():
    pass


def change_mysql():
    if get_ip_address('eth0') == webip:
        print '11'
        shells = "rm -rf  /web/site/www.0791look.com/config/"
        os.system(shells)

        shells = "cp -rf /web/site/www.0791look.com/config.salve/   /web/site/www.0791look.com/config/ "
        os.system(shells)


        shells = "unlink /web/site/www.0791look.com/uc_server/data/config.inc.php "
        os.system(shells)
        shells = "cp /web/site/www.0791look.com/uc_server/data/config.inc.php.salve  /web/site/www.0791look.com/uc_server/data/config.inc.php "
        os.system(shells)


        shells = "unlink /web/site/shop.0791look.com/data/config.php   "
        os.system(shells)
        shells = "cp /web/site/shop.0791look.com/data/config.php.salve  /web/site/shop.0791look.com/data/config.php "
        os.system(shells)







def change_websever():
    if get_ip_address('eth0') == webip:



        
        os.system('pkill rinetd ')
        os.system('/etc/init.d/nginx  stop ')
        time.sleep(10)
        os.system('rinetd -c /etc/rinetd.conf  ')
        os.system('chown -R shh_0791look /web/site/')
        os.system('/usr/user_sh/tongbu.sh')


    else:

        os.system('/etc/init.d/nginx  restart')
        os.system('/etc/init.d/mysqld  restart')
        os.system('chown -R shh_0791look /web/site/')



if __name__ == '__main__':
    m = True

    while m:


        try:

            status = urllib2.urlopen('http://www.0791look.com/status.php').read()


        except:
            time.sleep(10)
            try:
                status = urllib2.urlopen('http://www.0791look.com/status.php').read()
            except:
                time.sleep(10)
                try:
                    status = urllib2.urlopen('http://www.0791look.com/status.php').read()
                except:
                    status = 'change websever'






        print status
        if status == 'die':
            die_web()
        elif status == 'change mysql':
            change_mysql()
            m = False
        elif status == 'change websever':
            change_websever()
            m = False
        elif status == 'ok':
            pass
        else:
            change_websever()
            m = False
        time.sleep(3)






